package com.yan.crowd.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yan.crowd.constant.AccessPassResources;
import com.yan.crowd.constant.CrowdConstant;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 定义要拦截的资源.
 * false -> 允许被放行的资源
 * ture -> 不允许被放行的资源
 */
@Component
public class CrowdAccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();
        String servletPath = request.getServletPath();

        boolean contains = AccessPassResources.PASS_RES_SET.contains(servletPath);
        if (contains) {
            return false;
        }

        return !AccessPassResources.judgeCurrentServletPathStaticResource(servletPath);
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        HttpSession session = request.getSession();
        Object loginMember = session.getAttribute("user");
        if (loginMember == null) {
            HttpServletResponse response = currentContext.getResponse();
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,"请登录在尝试访问");
            try {
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
